package controller;

import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;

import org.activiti.engine.task.Task;

import wfm.activiti.ActivitiManager;
import wfm.entities.Customer;
import wfm.entities.Ticket;
import wfm.entities.User;
import wfm.entities.WFInfo;
import wfm.entities.Worker;
import wfm.query.QueryDao;

import com.web.util.WebUtils;

@ManagedBean(name="closeTicketController")
@SessionScoped
public class CloseTicketController {

	@ManagedProperty(value = "#{wfInfo}")
	private WFInfo wfInfo;
	
	@ManagedProperty(value="#{user}")
	private User user;
	
	@ManagedProperty(value="#{notes}")
	private String notes;
	

	private Ticket ticket;
		
	public CloseTicketController(){
		
	}
	
	@PostConstruct
	public void init() {
		ticket=(Ticket)QueryDao.getVariableToProcessById(wfInfo.getInstanceId(), "ticket");	
	}
	
	public Ticket getTicket() {
		return ticket;
	}
	public void setTicket(Ticket ticket) {
		this.ticket = ticket;
	} 
	
	public String finish(){
		String nextPage = "myTasks";

		// Retrieving Activiti engine
		ActivitiManager manager = ActivitiManager.getInstance();

		try {
			manager.getTaskRuntimeService().complete(wfInfo.getTaskId());

		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}

		// Check for any execution errors
		String instanceId = wfInfo.getInstanceId();
		
		Task task=QueryDao.getNextTaskAndSetAssignee(instanceId, this.user);  //holt sich den nächsten Task zur Gruppe und setzt Asignee
		
		if(task!=null){
			wfInfo.setTaskId(task.getId());
			nextPage = QueryDao.getFormKey(wfInfo.getTaskId());
		}

		return WebUtils.redirect(nextPage);
	}

	public WFInfo getWfInfo() {
		return wfInfo;
	}

	public void setWfInfo(WFInfo wfInfo) {
		this.wfInfo = wfInfo;
	}

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public String getNotes() {
		return notes;
	}

	public void setNotes(String notes) {
		this.notes = notes;
	}
	
}
